package com.katze.common.heart;

import com.katze.common.env.AppEnvironment;
import com.katze.common.heart.client.HeartBeatClient;
import com.katze.common.heart.server.HeartBeatServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import java.net.InetSocketAddress;


@ConditionalOnProperty(value = "app.heartbeat.mode", havingValue = "NioSocket")
@Deprecated
public class HeartBeatConfiguration {

    @Value("${server.address:#{systemProperties['local.address']}}")
    private String local;

    @Value("${server.port}")
    private Integer port;

    @ConditionalOnProperty(prefix = "server", name = "ping")
    @Bean(initMethod = "initialization", destroyMethod = "destroy")
    public HeartBeatClient heartBeatClient(@Value("${server.ping}") String remote) {
        String[] items = remote.split(":");
        InetSocketAddress address = InetSocketAddress.createUnresolved(items[0], Integer.parseInt(items[1]));
        HeartBeatClient heartBeatClient = new HeartBeatClient(address);
        heartBeatClient.active(()-> "Active@" + AppEnvironment.APP_NAME.getValue() + ":" + local + ":" + port);
        heartBeatClient.heartbeat();
        return heartBeatClient;
    }

    @ConditionalOnBean(HeartBeatHandle.class)
    @Bean(initMethod = "initialization", destroyMethod = "destroy")
    public HeartBeatServer heartBeatServer(HeartBeatHandle handle) {
        return new HeartBeatServer(new InetSocketAddress(port - 100), handle);
    }
}
